import { useUserStore } from "@/store/modules/user.store";

const userStore = useUserStore();
const baseUrl = process.env.API_BASE;

const http = (options: HttpOptions) => {
  options.url = baseUrl + options.url;
  if (userStore.token) {
    options.header = {
      ...options.header,
      Authorization: "Bearer " + userStore.token
    };
  }

  options.header = {
    ...options.header,
    "Content-Type": "application/json"
  };

  if (options.params) {
    options.url +=
      "?" +
      Object.keys(options.params)
        .map((key) => `${key}=${options.params?.[key]}`)
        .join("&");
  }

  return new Promise<{ success: boolean; data: any }>((resolve, reject) => {
    uni.showLoading({
      title: "加载中...",
      mask: true
    });
    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data as any);
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        reject(err);
      },
      complete: () => {
        uni.hideLoading();
      }
    });
  });
};

export const got = Object.assign(http, {
  upload: (options: HttpUploadOptions) => {
    options.url = baseUrl + options.url;
    if (userStore.token) {
      options.header = {
        ...options.header,
        Authorization: "Bearer " + userStore.token
      };
    }

    if (options.params) {
      options.url +=
        "?" +
        Object.keys(options.params)
          .map((key) => `${key}=${options.params?.[key]}`)
          .join("&");
    }
    return new Promise<{ success: boolean; data: any }>((resolve, reject) => {
      uni.showLoading({
        title: "加载中...",
        mask: true
      });
      uni.uploadFile({
        ...options,
        name: "file",
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(JSON.parse(res.data));
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          reject(err);
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    });
  }
});

type HttpOptions = Omit<Parameters<typeof uni.request>[0], "success" | "fail" | "complete"> & {
  params?: Record<string, any>;
};

type HttpUploadOptions = Omit<
  Parameters<typeof uni.uploadFile>[0],
  "success" | "fail" | "complete" | "name"
> & {
  params?: Record<string, any>;
};
